<template>
  <ContentDetailWrap :title="t('warehouse.add')">
    <template #header>
      <BaseButton @click="go(-1)">
        {{ t('common.back') }}
      </BaseButton>
      <BaseButton type="primary" :loading="loading" @click="handleSubmit(formRef)">
        {{ t('action.save') }}
      </BaseButton>
    </template>
    <!--    表单-->
    <el-form
      :model="form"
      ref="formRef"
      :rules="rules as FormRules"
      :label-width="isMobile ? '108px' : '150px'"
      class="form-container"
    >
      <el-form-item
        :label="t('MerchandiseOffersBaskets.product')"
        prop="product_name"
        :class="isMobile ? 'w-full' : 'w-50%'"
      >
        <el-input v-model="form.product_name" clearable disabled>
          <template #append>
            <el-button size="small" text type="primary" @click="handleOpenProduct">选择</el-button>
          </template>
        </el-input>
      </el-form-item>
      <!--      分割线-->
      <div class="divider"></div>
      <el-form-item
        :label="t('MerchandiseOffersBaskets.warehouse')"
        prop="wid"
        :class="isMobile ? 'w-full' : 'w-50%'"
      >
        <el-tree-select
          v-model="form.wid"
          :data="warehouseList"
          filterable
          check-strictly
          @change="handleWarehouseChange"
          :render-after-expand="false"
        />
      </el-form-item>

      <el-form-item
        :label="t('purchase.ccname_ids')"
        :class="isMobile ? 'w-full' : 'w-50%'"
        prop="ccname_ids"
        required
      >
        <el-select
          v-model="form.ccname_ids"
          filterable
          multiple
          :placeholder="'请选择' + t('purchase.ccname_ids')"
        >
          <el-option label="全球" :value="0" />
          <el-option
            v-for="item in sellableList"
            :selected="item.is_sellable"
            :key="item.id"
            :label="item.cc_name"
            :value="item.id"
            :disabled="form.ccname_ids?.includes(0)"
          />
        </el-select>
      </el-form-item>

      <el-form-item
        :label="t('MerchandiseOffersBaskets.is_futures')"
        prop="is_futures"
        :class="isMobile ? 'w-full' : 'w-50%'"
      >
        <el-select
          v-model="form.is_futures"
          :filterable="true"
          :placeholder="t('MerchandiseOffersBaskets.is_futures')"
          :clearable="false"
        >
          <el-option
            v-for="item in isFuturesList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item
        :label="t('MerchandiseOffersBaskets.arrival_date')"
        prop="arrival_date"
        v-if="form.is_futures != 0"
        :class="isMobile ? 'w-full' : 'w-50%'"
      >
        <el-date-picker
          v-model="form.arrival_date"
          type="date"
          placeholder="到货日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>

      <el-form-item
        :label="t('MerchandiseOffersBaskets.available_qty')"
        prop="available_qty"
        :class="isMobile ? 'w-full' : 'w-50%'"
      >
        <el-input-number
          v-model="form.available_qty"
          disabled
          :min="0"
          :precision="0"
          placeholder="请输入"
        />
      </el-form-item>

      <el-form-item :label="t('MerchandiseOffersBaskets.is_sale')">
        <el-radio-group class="m-l-20px" v-model="form.is_sale">
          <el-radio v-for="item in isSaleList" :key="item.value" :label="item.value" disabled
            >{{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item
        :label="t('MerchandiseOffersBaskets.allow_zero_stock_sale')"
        :class="isMobile ? 'w-full' : 'w-50%'"
      >
        <el-radio-group class="m-l-20px" v-model="form.allow_zero_stock_sale">
          <el-radio v-for="item in alloZeroList" :key="item.value" :label="item.value" disabled
            >{{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <Gradient ref="gradientRef" :wid="form.wid" />
  </ContentDetailWrap>
  <DialogCustomerChecked
    ref="DialogCustomerCheckedRef"
    @expose-multiple-data="handleCustomerSelect"
  />

  <!--  选择商品弹框-->
  <PrimarPidDialog ref="DialogShopCheckedRef" @expose-multiple-data="handleProductSelect" />
</template>

<script setup lang="ts">
import { ContentDetailWrap } from '@/components/ContentDetailWrap'
import { ElButton, ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { getEnumApi } from '@/api/warehouse/merchandiseOffers/index'
import DialogCustomerChecked from '@/views/Order/OrderReturn/components/DialogCustomerChecked/index.vue'
import PrimarPidDialog from '@/components/Dialog/src/Product.vue'
import Gradient from './components/Gradient/index.vue'
import { saveBasketsApi } from '@/api/inventory/index'
import { getSellableListApi } from '@/api/regionCountry/index'
import { ref, onMounted, nextTick, computed, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { useRouter } from 'vue-router'

// 移动端检测
import { useAppStore } from '@/store/modules/app'
const appStore = useAppStore()
const isMobile = computed(() => appStore.getMobile)
// 类型定义
interface FormState {
  productid: string
  product_name: string
  product_id: string
  is_futures: number | string
  arrival_date: string
  available_qty: number
  wid: string
  is_sale: number
  allow_zero_stock_sale: number
  ccname_ids: number[]
  customer_id?: string
  owner?: string
  partner?: string
  customer_name?: string
  order_id?: string
  order_no?: string
}

interface SellableItem {
  id: number
  cc_name: string
  is_sellable: boolean
}

interface EnumItem {
  value: number
  label: string
}

// 常量定义
const DEFAULT_FORM_STATE: FormState = {
  productid: '',
  product_name: '',
  product_id: '',
  is_futures: '',
  arrival_date: '',
  available_qty: 0,
  wid: '',
  is_sale: 1,
  allow_zero_stock_sale: 1,
  ccname_ids: []
}

// 响应式状态
const { t } = useI18n()
const { push, go } = useRouter()
const loading = ref<boolean>(false)
const formRef = ref<FormInstance>()
const gradientRef = ref<InstanceType<typeof Gradient> | null>(null)
const DialogCustomerCheckedRef = ref()
const DialogShopCheckedRef = ref()

// 枚举数据
const warehouseList = ref<EnumItem[]>([])
const isFuturesList = ref<EnumItem[]>([])
const isSaleList = ref<EnumItem[]>([])
const alloZeroList = ref<EnumItem[]>([])
const firstWarehouseList = ref<EnumItem[]>([])
const copyIsFuturesList = ref<EnumItem[]>([])
const first_warehouse = ref<number[]>([])
const sellableList = ref<SellableItem[]>([])

// 计算属性
const formattedIsFutures = computed(() => {
  return form.value.is_futures === 1 ? '是' : '否'
})

// 表单状态
const form = ref<FormState>({ ...DEFAULT_FORM_STATE })

// 表单验证规则
const rules = ref<FormRules>({
  product_name: [
    {
      required: true,
      message: t('MerchandiseOffersBaskets.productMsg'),
      trigger: 'change'
    }
  ],
  is_futures: [
    {
      required: true,
      message: t('MerchandiseOffersBaskets.isFuturesMsg'),
      trigger: 'change'
    }
  ],
  wid: [
    {
      required: true,
      message: t('MerchandiseOffersBaskets.warehouseMsg'),
      trigger: 'change'
    }
  ],
  is_sale: [
    {
      required: true,
      message: t('MerchandiseOffersBaskets.isSaleMsg'),
      trigger: 'change'
    }
  ],
  arrival_date: [
    {
      required: true,
      message: t('MerchandiseOffersBaskets.arrivaldateMsg'),
      trigger: 'change'
    }
  ]
})

// 方法定义
const handleCustomerSelect = (customers: any[]) => {
  if (!customers?.length) return

  const customer = customers[0]
  Object.assign(form.value, {
    customer_id: customer.id,
    owner: customer.owner_id,
    partner: customer.partner,
    customer_name: customer.cusname,
    order_id: '',
    order_no: ''
  })
}

const handleOpenProduct = () => {
  nextTick(() => {
    if (!DialogShopCheckedRef.value) return

    DialogShopCheckedRef.value.dialogVisible = true
    DialogShopCheckedRef.value.initialize(
      form.value.product_id ? [{ cname: form.value.product_name, id: form.value.product_id }] : [],
      form.value.customer_id
    )
  })
}

const handleProductSelect = (products: any[]) => {
  if (!products?.length) return

  const product = products[0]
  form.value.product_name = product.cname
  form.value.product_id = product.id
}

const handleWarehouseChange = async (val: string) => {
  if (!val) {
    sellableList.value = []
    return
  }

  // 更新期货类型列表
  nextTick(() => {
    isFuturesList.value = copyIsFuturesList.value
    if (!first_warehouse.value.includes(Number(val))) {
      isFuturesList.value = isFuturesList.value.filter((item) => item.value !== 2)
      if (form.value.is_futures === 2) {
        form.value.is_futures = ''
      }
    }
    gradientRef.value?.queryDropDownBox()
  })

  // 获取可售列表
  const resp = await getSellableListApi({ id: val })
  if (resp?.data?.list) {
    sellableList.value = resp.data.list
    form.value.ccname_ids = resp.data.list.filter((item) => item.is_sellable).map((item) => item.id)
  }
}

const handleSubmit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return

  const valid = await formEl.validate()
  if (!valid) return

  try {
    const gradientData = await gradientRef.value?.gradientSubmit()
    const params = {
      ...form.value,
      product_prices: gradientData?.product_prices
    }

    const resp = await saveBasketsApi(params)
    if (resp.code === 0) {
      ElMessage.success(t('MerchandiseOffersBaskets.createSucMsg'))
      push({ path: '/warehouse/merchandiseOffers' })
    }
  } catch (error) {
    console.error('Submit failed:', error)
  }
}

// 初始化
const initializeData = async () => {
  const resp = await getEnumApi({ field: 'ALL' })
  if (!resp?.data) return

  warehouseList.value = resp.data.level_warehouse
  firstWarehouseList.value = resp.data.warehouse
  isFuturesList.value = resp.data.is_futures
  copyIsFuturesList.value = resp.data.is_futures
  isSaleList.value = resp.data.is_sale
  alloZeroList.value = resp.data.allow_zero_stock_sale
  first_warehouse.value = resp.data.warehouse.map((warehouse) => warehouse.value)
}

// 生命周期钩子
onMounted(initializeData)

// 监听 ccname_ids 的变化
watch(
  () => form.value.ccname_ids,
  (newVal) => {
    if (newVal?.includes(0) && newVal.length > 1) {
      // 如果选择了全球且还有其他选项，只保留全球选项
      nextTick(() => {
        form.value.ccname_ids = [0]
      })
    }
  },
  { deep: true }
)
</script>
<style lang="less" scoped>
.form-container {
  .divider {
    @apply h-1px w-full bg-[#c8c9cc] my-10px;
  }
}
</style>
